from mySQL import do
from index import dbObject

# class Device:
#     def __init__(self, sqlDevice):  # id,name,address,state,serial,time
#         self.device_node_id = sqlDevice[0]
#         self.name = sqlDevice[1]
#         self.address = sqlDevice[2]
#         self.status = sqlDevice[3]
#         self.description = sqlDevice[4]
#         self.second = sqlDevice[5].strftime("%Y-%m-%d %H:%M:%S")  # isoformat()
#         self.monitor = ""
#         self.alarm = 0
#         self.unit = ""

#
# def GetDevicesBySqlDevices(sqlDevices):
#     return map(lambda item: Device(item), sqlDevices) if sqlDevices is not None else None


# "1": {"datetime": "2018-12-13", "peak": {"alarm": 1, "value": 3, "unit": "dB"}}
# def GetMonitorDataByDevices(devices):
#     def GetDictBySensor(data):  # id,name,value,min,max,unit
#         alarmValue = 0 if data[2] > data[3] and data[2] < data[4] else 1
#         return {data[1]: {"alarm": alarmValue, "value": data[2], "unit": data[5]}}
#
#     dict = {};
#     for item in devices:
#         dict[str(item.device_node_id)] = {"datetime": item.second}
#         dictNode = dict[str(item.device_node_id)]
#         monitorDatas = do.sensorByDid(item.device_node_id)
#         for sensor in monitorDatas:
#             sensorDict = GetDictBySensor(sensor)
#             dictNode[sensor[1]] = sensorDict[sensor[1]]
#     # print(dict)
#     return dict


# {"peak": {"alarm": [1, 1, 0, 1], "value": [0, 0, 2, 4], "unit": "mv"},
#                      "datetime": ["2018-03-16 09:57:59", "2018-03-16 ,09:56:49", "2018-03-16 08:19:02",
#                                   "2018-03-16 03:40:15"]}
#
# ((1, 'UHF', 5.0, 'V', datetime.datetime(2018, 3, 29, 10, 50, 44), -1000.0, 1000.0), (2, 'UHF', 72.0, 'V', datetime.datetime(2018, 3, 30, 10, 50, 44), -1000.0, 1000.0))
# def GetHistoryDataBySqlHistorys(sqlHistorys):
#     dict = {}
#     for item in sqlHistorys:
#         if (dict.__contains__(item[1]) == False):
#             dict[item[1]] = {"alarm": [], "value": [], "unit": item[3], "datetime": []}
#     for item in sqlHistorys:
#         node = dict[item[1]]
#         alarms, values, datetimes = node["alarm"], node["value"], node["datetime"]
#         alarms.append(0 if item[2] > item[5] and item[2] < item[6] else 1)
#         values.append(item[2])
#         datetimes.append(item[4].strftime("%Y-%m-%d %H:%M:%S"))
#     return dict

def assign_device(d_id):
    deviceUsers = dbObject.Device(d_id).getUsers()
    allUsers = dbObject.getAllUsersObj()
    users = []
    for item in allUsers:
        if item.state == 'active':
            users.append(item)
    for item in users:
        item.state = "leaving"
        for itemDevice in deviceUsers:
            if item.id == itemDevice.id:
                item.state = "active"
                break
        item.password = "******"
    return dbObject.obj_to_dict(users)


def attach_user_device(d_id, user_list):
    beforeAssign = assign_device(d_id)
    for idx in range(0, len(beforeAssign)):
        beforUsers, afterUsers = beforeAssign[idx], user_list[idx]
        print(afterUsers)
        if beforUsers["state"] == 'active' and afterUsers["state"] != 'active':
            do.updateDeviceUserState(d_id, afterUsers['id'], "leaving")
        elif beforUsers["state"] != 'active' and afterUsers["state"] == 'active':
            do.updateDeviceUserState(d_id, afterUsers["id"], "active")


def attach_sensor_device(d_id, sensor_list):
    beforeSensors = do.allSensorByDid(d_id)
    for idx in range(0, len(beforeSensors)):
        before, after = list(beforeSensors[idx]), sensor_list[idx]
        if before != after:
            do.updateSensor(after)
            print("updateSensor", before, after)
